class EventsController < ApplicationController
  before_filter :require_login
  before_filter :current_user
  
  # GET /events
  # GET /events.xml
  def index
    @page_title = "Events"

    @events = Event.paginate :per_page => 10, :page => params[:page],
                             :order => 'begin_date DESC' 

    @new_events = Array.new 
    @edited_events = Array.new

    if @current_user.administrator
      @new_events = Event.where(:approved => nil)
      @edited_events = Event.where(:approved => false)
    end

    @events_this_week = Event.where("begin_date >= :bd AND begin_date <= :ed", 
                                    :bd => Date.today.next_week - 7.days,
                                    :ed => Date.today.next_week).sort! {|e1, e2| e1.begin_date <=> e2.begin_date}
      

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @events }
    end
  end

  # GET /events/1
  # GET /events/1.xml
  def show
    @page_title = "Event Details"
    @event    = Event.find(params[:id])

    @approvable = @current_user.authorize(Event::APPROVE, @event)

    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @event }
    end
  end

  # GET /events/new
  # GET /events/new.xml
  def new
    @page_title = "New Event"
    @event = Event.new

    if !@current_user.validated
      flash[:error] = "User must be validated by an administrator before creating events"
      redirect_to :back
      return
    end

    @custom_start_date = nil
    if params[:month] && params[:day] && params[:year]
      @custom_start_date = Date.new(params[:year].to_i, params[:month].to_i, params[:day].to_i)
    end

    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @event }
      format.js
    end
  end

  # GET /events/1/edit
  def edit
    @page_title = "Edit Event"
    @event = Event.find(params[:id])
    @approvable = @current_user.authorize(Event::APPROVE, @event)

    #this value will replace the event's owner textfield's default text (owner_id)
    owner = User.find(@event.owner_id)
    @owner_username = owner.nil? ? "User does not exist" : owner.username

    if params[:q]
      @usernames = User.all(:conditions => ["username like ?", params[:q] + '%'])
    else
      @usernames = User.all
    end

    if !@current_user.authorize(Event::EDIT, @event)
      flash[:error] = "User does not have the rights to edit this event" 
      redirect_to :back
      return
    end

    respond_to do |format|
      format.html
    end
  end

  # POST /events
  # POST /events.xml
  def create
    @page_title = "Create Event"

    # Browsers have been observed to do two things:
    #  1.) Give the ID of the user submitted
    #  2.) Give the Username of the user submitted
    # This accounts for such behavior
    owner = nil
    if !(params[:event][:owner_id] =~ /^\d*$/).nil? #browser supplies id
      owner = User.find(params[:event][:owner_id])
    else    # browser supplies username
      owner = User.where(:username => params[:event][:owner_id]).first
    end

    if owner.nil?
      flash[:error] = "User specified for the owner of the event does not exist.  Please enter a valid username"
      redirect_to :back
      return
    end

    # need to replace :owner_id as it originally contains username
    params[:event][:owner_id] = owner.id
    @event = Event.new(params[:event])

    @event.creator = @current_user 

    if !@current_user.authorize(Event::CREATE, @event)
      flash[:error] = "User does not have the rights to create this event"
      redirect_to :back
      return
    end

    message = "Event was successfully created."
    if !@current_user.authorize(Event::APPROVE, @event)
      message = "Event was successfully created, but needs approval from an authorized user."
      @event.approved = false
    end

    respond_to do |format|
      if @event.save
        format.html { redirect_to(calendar_path, :notice => message) }
        format.xml  { render :xml => @event, :status => :created, :location => @event }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @event.errors, :status => :unprocessable_entity }
      end
    end
  end

  # PUT /events/1
  # PUT /events/1.xml
  def update
    @event = Event.find(params[:id])

    #enforce event approval security policy, respond to user accordingly
    message = "Event was successfully updated."
    if !@current_user.authorize(Event::APPROVE, @event)
      message = "Event was successfully updated, but needs approval from an authorized user."
      params[:event][:approved] = false
      params[:event][:approver_id] = @event.approver_id
    elsif params[:event][:approved] && !@event.approved
      params[:event][:approver_id] = @current_user
    end

    params[:event][:creator_id] = @event.creator_id

    @event.updated_at = Time.now

    respond_to do |format|
      if @event.update_attributes(params[:event]) && @event.save
        format.html { redirect_to(@event, :notice => message) }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @event.errors, :status => :unprocessable_entity }
      end
    end
  end

  # DELETE /events/1
  # DELETE /events/1.xml
  def destroy
    @event = Event.find(params[:id])

    if !@current_user.authorize(Event::DELETE, @event)
      flash[:error] = "User does not have the rights to delete this event."
      redirect_to :back
      return
    end

    @event.destroy

    respond_to do |format|
      format.html { redirect_to(events_url) }
      format.xml  { head :ok }
    end
  end

  def approve
    @page_title = "Approve Event"

    @event_to_approve = Event.find(params[:id])

    # check permissions
    if !@current_user.authorize(Event::APPROVE, @event_to_approve)
      flash[:error] = "User does not have the rights to approve this event."
      redirect_to :back
      return
    end

    @current_user.approve_event(@event_to_approve)

    respond_to do |format|
      format.html { redirect_to(:back, :notice => 'Event was successfully approved.') }
      format.json { head :ok }
    end
  end

  def revoke_approval
    @page_title = "Revoke Approval"
    @event_to_revoke = Event.find(params[:id])

    # check permissions
    if !@current_user.authorize(Event::APPROVE, @event_to_approve)
      flash[:error] = "User does not have the rights to revoke approval of this event."
      redirect_to :back
      return
    end

    @current_user.revoke_approval(@event_to_revoke)

    respond_to do |format|
      format.html { redirect_to(@event_to_revoke, :notice => 'Event approval was successfully revoked.') }
      format.json { head :ok }
    end
  end

  def import

  end
end
